package com.wink_172.library.view

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wink_172.library.adapter.HomeListAdapter
import com.wink_172.library.model.Constants
import java.util.*

open class CustomRecyclerView : RecyclerView {
    open var lastVisibleItem = 0
    open var fistVisibleItem = 0
    open var isLoadingMore = false //正在加载更多
    open var currentPage = 1

    //单页数量 用作翻页  可外界动态改变  请注意如果第一页返回的数据量小于指定的pageCount 则不会参与翻页事件，经常会犯的错误
    //单页数量 用作翻页  可外界动态改变  请注意如果第一页返回的数据量小于指定的pageCount 则不会参与翻页事件，经常会犯的错误
    open var pageCount=Constants.COUNT //单页数量 用作翻页  可外界动态改变  请注意如果第一页返回的数据量小于指定的pageCount 则不会参与翻页事件，经常会犯的错误

    open var mSelectMode = false//true选择模式

    open var mLibCallback: com.wink_172.library.callback.ICallback? = null
    open var mCallback: ICallback? = null  //兼容旧版本 逐渐替换  以后不会用到了
    fun setLibCallback(callback: com.wink_172.library.callback.ICallback?) {
        mLibCallback = callback
    }
    fun setCallback(callback: ICallback?) {
        mCallback = callback
    }



    interface ICallback {
        fun onLoadMore()
    }

    constructor(context: Context?) : super(context!!) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {}

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context!!, attrs, defStyle) {}

    override fun setOverScrollMode(overScrollMode: Int) { //去除阴影
        super.setOverScrollMode(overScrollMode)
        //        super.setOverScrollMode(OVER_SCROLL_NEVER);
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        initView()
    }

    fun initView() {}

    /**
     * Compatible with  兼容旧版本true
     *
     */
    fun init(adapter: Adapter<*>?, compatible: Boolean) {
        if (compatible) { //自给自足
            val list: MutableList<Any> = ArrayList()
            val homeListAdapter = HomeListAdapter(context, list, this)
            setAdapter(homeListAdapter)
        } else {
            setAdapter(adapter)
        }
    }




    override fun onScrollStateChanged(state: Int) {
        super.onScrollStateChanged(state)
        val count = adapter!!.itemCount

        //请注意 如果自己筛选了数据导致列表当前展示数量不超过pageCount，是不会触发下面的事件的，下次遇到不要再问为什么了，可以把参数params数量增多就行了
        //请注意 如果自己筛选了数据导致列表当前展示数量不超过pageCount，是不会触发下面的事件的，下次遇到不要再问为什么了
//        Log.e(TAG, "onScrollStateChanged: ====>>lastVisibleItem:" + lastVisibleItem + "|    count:" + count + "|    "+"   fistVisibleItem:"+fistVisibleItem);
        if (state == SCROLL_STATE_IDLE && lastVisibleItem > 0 && lastVisibleItem == count - 1 && count >=pageCount) {
            //失效是因为其他类型未定义LinearLayoutManager
            // 注意如果存在默认尾部item的话这里>0需要调整
            //mLastVisibleItem在未满一屏的时候就会出现各种问题，但是分页查询一页肯定要大于一定数量的,如果都满足不了还要分页干什么
            Log.e(TAG, "加载更多！！====>>")
            if (mCallback != null) {
                mCallback!!.onLoadMore()
            }
        }

        if(mLibCallback!=null){
//            onScrollStateChanged
            mLibCallback!!.onSendEvent(Constants.EVENT_10,state,fistVisibleItem,lastVisibleItem)
        }
    }

    /**
     *把列表数量超过容器然后再滚动 dy就会有
     * */
    override fun onScrolled(dx: Int, dy: Int) {
        super.onScrolled(dx, dy)

        val layoutManger = layoutManager ?: return
        if (layoutManger is GridLayoutManager) {
            val gridLayoutManager = layoutManger
            lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition()
            fistVisibleItem = gridLayoutManager.findFirstVisibleItemPosition()
        } else if (layoutManger is LinearLayoutManager) {
            val linearManger = layoutManger
            lastVisibleItem = linearManger.findLastVisibleItemPosition()
            fistVisibleItem = linearManger.findFirstVisibleItemPosition()
        }
        if(mLibCallback!=null){
//            onScrolled
            mLibCallback!!.onSendEvent(Constants.EVENT_11,fistVisibleItem,lastVisibleItem)
            mLibCallback!!.onSendEvent( Constants.EventEnum.列表滚动.ordinal,dx,dy)
        }
    }

    /**
     * 请注意哦
     * 如果列表还没有滚动到该item
     * 或者页面没有显示该itemview
     * 取到的是空的
     * 需要scrollToPositionWithOffset  准确的到达该pos  要让该view在列表中显示出来
     * */
    fun findViewByPos(pos: Int): View? {
        var view: View? = null

        val layoutManger = layoutManager ?: return null
        if (layoutManger is GridLayoutManager) {
            view = layoutManger.findViewByPosition(pos)
        } else if (layoutManger is LinearLayoutManager) {
            view = layoutManger.findViewByPosition(pos)
        }
        return view
    }

    fun scrollToEnd() {
        val count = adapter!!.itemCount
        if (count > 1) {
            scrollToPosition(count - 1)
        }
        //        super.smoothScrollToPosition(count);
    }

    /**
     * 准确的到达指定pos  而不是只要屏幕中看到了但是存在一大段间距
     * */
    fun scrollToPositionWithOffset(position: Int) {
        val layoutManger = layoutManager ?: return
        if (layoutManger is GridLayoutManager) {
            val linearManger = layoutManger
        } else if (layoutManger is LinearLayoutManager) {
            layoutManger.scrollToPositionWithOffset(position, 0)
        }
    }

    val isScrollTop: Boolean
        get() = computeVerticalScrollOffset() == 0

    override fun requestChildFocus(child: View, focused: View) {
        super.requestChildFocus(child, focused)
        onFocusChangeListener?.let {

            it.onFocusChange(child, false)
            it.onFocusChange(focused, true) }

        }
    }

private const val TAG = "CustomRecyclerView"

